<?php
$pageTitle = "修改密码";
include 'header.php';

// 初始化错误信息变量
$error = '';
$success = '';

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $old_password = $_POST['old_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // 验证输入
    if (empty($old_password) || empty($new_password) || empty($confirm_password)) {
        $error = '所有字段都是必填的';
    } elseif ($new_password !== $confirm_password) {
        $error = '新密码和确认密码不匹配';
    } elseif (strlen($new_password) < 6) {
        $error = '新密码必须至少包含6个字符';
    } else {
        // 获取当前用户信息
        $stmt = $pdo->prepare("SELECT id, password FROM users WHERE id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $user = $stmt->fetch();
        
        // 验证旧密码
        if ($user && password_verify($old_password, $user['password'])) {
            // 更新密码
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
            if ($stmt->execute([$hashed_password, $user['id']])) {
                $success = '密码修改成功';
            } else {
                $error = '密码修改失败';
            }
        } else {
            $error = '旧密码不正确';
        }
    }
}
?>

<div class="row">
    <div class="card login-card">
        <div class="card-body">
            <h2 class="card-title text-center mb-4">修改密码</h2>

            <?php if ($error): ?>
                <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
            <?php endif; ?>
            <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                <div class="mb-3">
                    <label for="old_password">旧密码：</label>
                    <input type="password" class="form-control" id="old_password" name="old_password" required>
                </div>
                
                <div class="mb-3">
                    <label for="new_password">新密码：</label>
                    <input type="password" class="form-control" id="new_password" name="new_password" required>
                    <small class="form-text text-muted">至少6个字符</small>
                </div>
                
                <div class="mb-3">
                    <label for="confirm_password">确认新密码：</label>
                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                </div>
                
                <button type="submit" class="btn btn-primary">修改密码</button>
                <a href="index.php" class="btn btn-secondary">取消</a>
            </form>
        </div>
    </div>
</div>

<!-- 引入脚本 -->
<?php include 'footer.php'; ?>
